package org.jeecg.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CommonConstant;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author by Administrator
 * @desc:
 * @since 2024-12-06 星期五 12:39:55
 */
@Order(0)
@Slf4j
@Component
@WebFilter(urlPatterns = "/**", filterName = "TenantFilter")
public class TenantFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑（如果需要）
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String tenantId = httpRequest.getHeader(CommonConstant.TENANT_ID);
            if (tenantId != null) {
                TenantContext.setTenant(tenantId);
            }

            try {
                // 继续处理请求
                chain.doFilter(request, response);
            }finally {
                // 清理线程本地变量
                TenantContext.clear();
            }
        } else {
            // 如果请求不是 HttpServletRequest 类型，则直接继续处理请求
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        // 销毁逻辑（如果需要）
    }
}